import os

from base.pdf_to_images import pdf_to_images
from base.read_excel import read_excel
import re


def get_number_from_filename(filename):
    # 使用正则表达式从文件名中提取数字部分
    matches = re.findall(r'\d+', filename)
    if matches:
        return int(matches[0])
    else:
        return 0


def get_folder_structure(folder_path):
    result = {'name': os.path.basename(folder_path), 'type': 'folder', 'children': []}

    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        output_path = ''
        read_info = []
        if os.path.isdir(item_path):
            result['children'].append(get_folder_structure(item_path))
        else:
            file_name, file_extension = os.path.splitext(item)
            file_path = item_path.replace('\\', '/')
            file_type = 'file'
            if file_extension.lower() == '.pdf':
                # 将pdf转成图片，并输出导出地址
                output_path = pdf_to_images(file_path)
                file_type = 'pdf'
            elif file_extension.lower() == '.xls' or file_extension.lower() == '.xlsx':
                read_info = read_excel(file_path)
                file_type = 'xls'

            result['children'].append({'name': item, 'type': file_type, 'path': file_path, 'output_path': output_path,
                                       'read_info': read_info})

    # 按照数字顺序对文件名进行排序
    result['children'] = sorted(result['children'], key=lambda x: get_number_from_filename(x['name']))

    return result
